import socket
import sqlite3
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import sys

# 连接数据库
conn = sqlite3.connect('mydb.db')
cursor = conn.cursor()

# 创建表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS state (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        states TEXT,
        timestamp REAL
    )
''')
conn.commit()

# 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '114.215.65.250'
port = 4509
sock.connect((host, port))

# 发送登陆命令
username = 'farsight6'
password = '123456'
login_cmd = f'KEY:{username}+{password}'
sock.sendall(login_cmd.encode())

# 接收服务器响应
respond = sock.recv(1024).decode()  
print(respond)

# 定义停止标志
stop_flag = threading.Event()

def receive_data():
    """持续接收服务器数据的线程函数"""
    try:
        while not stop_flag.is_set():
            data = sock.recv(1024).decode(errors='ignore')
            if not data:
                print('接收信息失败')
                stop_flag.set()  # 通知其他线程停止
                sys.stdin.close()
                break
            print(f"[接收] {data}")
            if "logout" in data:
                print('收到退出指令')
                stop_flag.set()  # 通知其他线程停止
                sys.stdin.close()
                break
    except Exception as e:
        print(f"接收线程异常: {e}")
        stop_flag.set()
        sys.stdin.close()

def send_commands():
    """处理用户输入并发送命令的线程函数"""
    try:
        while not stop_flag.is_set():
            try:
                a = input('请输入指令：') # 防止停止代码logout顶掉device_name
                

                device_name = input('请输入设备名称：')
                if stop_flag.is_set(): break
            
                sub_device_name = input('请输入子设备名称：')
                if stop_flag.is_set(): break
            
                do_cmd = input('请输入命令：')
                if stop_flag.is_set(): break
            
                cmd = f'ORDER:{device_name}+{sub_device_name}={do_cmd}'
                print(f"[发送] {cmd}")
                sock.sendall(cmd.encode())
            except (ValueError, OSError):
                print("输入已关闭，退出发送线程")
                break
    except Exception as e:
        print(f"发送线程异常: {e}")
        stop_flag.set()

if 'login-success' in respond:
    print('登陆成功')
    # 创建线程池（最大2个线程）
    with ThreadPoolExecutor(max_workers=2, thread_name_prefix='socket_thread') as executor:
        # 提交两个任务到线程池
        recv_future = executor.submit(receive_data)
        send_future = executor.submit(send_commands)
        
        # 等待停止信号（最长等待0.5秒检查一次）
        while not stop_flag.is_set():
            time.sleep(0.1)

        if not recv_future.done():
            recv_future.cancel()
        if not send_future.done():
            send_future.cancel()
else:
    print('登录失败')

# 资源清理
cursor.execute("select * from state")
for row in cursor.fetchall():
    print(row)

sock.close()
cursor.close()
conn.close()